package org.rcgwt.sample.client;

import java.util.List;

import org.rcgwt.client.ui.grid.RcGrid;
import org.rcgwt.client.ui.grid.RcGridConfig;

import org.rcgwt.client.ui.grid.provider.AbstractRpcRowsProvider;
import org.rcgwt.client.ui.grid.provider.IRowsProvider;
import org.rcgwt.client.ui.grid.reflect.EditableReflectedDataModel;
import org.rcgwt.client.ui.grid.theme.VistaGridTheme;
import org.rcgwt.sample.client.model.Employee;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

public class GridRpcExample extends Widget implements EntryPoint {

    private EmployeeServiceAsync employeeService = null;

    public void onModuleLoad() {

        Log.setUncaughtExceptionHandler();

        RcGridConfig config = new RcGridConfig();
        config.setTheme(VistaGridTheme.SINGLETON);
        config.setSelectable(true);
        EditableReflectedDataModel<Employee> model = new EditableReflectedDataModel<Employee>(
                Employee.class);
        config.setDataModel(model);
        config.setPageSize(8);

        initService();
        IRowsProvider<Employee> dataProvider = new AbstractRpcRowsProvider<Employee>() {

            @Override
            protected void load(AsyncCallback<List<Employee>> callback) {
                employeeService.getEmployees(callback);

            }
        };

        RcGrid grid = new RcGrid(config);
        RootPanel.get().add(grid);

        dataProvider.load(model);
    }

    private void initService() {
        // Initialize the service.
        //
        employeeService = (EmployeeServiceAsync) GWT
                .create(EmployeeService.class);

        // By default, we assume we'll make RPCs to a servlet, but see
        // updateRowData(). There is special support for canned RPC
        // responses.
        // (Which is a totally demo hack, by the way :-)
        // 
        ServiceDefTarget target = (ServiceDefTarget) employeeService;

        // Use a module-relative URLs to ensure that this client code can
        // find
        // its way home, even when the URL changes (as might happen when you
        // deploy this as a webapp under an external servlet container).
        String moduleRelativeURL = GWT.getModuleBaseURL() + "employee";
        target.setServiceEntryPoint(moduleRelativeURL);
    }

}
